﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace com.ReinforceLab.AudioModem.SignalTrace
{
    public class CSVFormatter
    {
        #region Public methods
        public void Dump(System.IO.TextWriter writer, double timestep, ITracer[] recorders)
        {            
            if (recorders.Length <= 0)
                return;

            // signal length
            int sample_length = int.MaxValue;
            foreach (var recorder in recorders)
                sample_length = Math.Min(recorder.Signal.Count<double>(), sample_length);

            // signal name
            writer.Write("\"time\"");
            foreach(var rec in recorders)
                writer.Write(String.Format("\", {0}\"", rec.SignalName));
            writer.WriteLine();
            
            // value dump
            List<double []> signals = new List<double []>();
            foreach (var rec in recorders)
                signals.Add( rec.Signal.ToArray<double>() );                

            for (int index = 0; index < sample_length; index++)
            {
                writer.Write(String.Format("{0:E}", index * timestep));
                foreach (var sig in signals)
                    writer.Write(String.Format(", {0:E}", sig[index]));
                writer.WriteLine();
            }
        }
        #endregion
    }
}
